package com.jingdianjichi.circle.server.config.websocket;

import com.jingdianjichi.circle.server.util.LoginUtil;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import javax.websocket.HandshakeResponse;
import javax.websocket.server.HandshakeRequest;
import javax.websocket.server.ServerEndpointConfig;
import java.util.List;
import java.util.Map;

/**
 * 我们的websocet不是谁都可以连接的,我们要做一下鉴权的
 */
@Component
public class WebSocketServerConfig extends ServerEndpointConfig.Configurator {

    //这个就是你随便链接
    //这里就是鉴权逻辑亲
    @Override
    public boolean checkOrigin(String originHeaderValue) {
        return true;
        /*
            //获得连接参数
            ServletRequestAttributes servletRequestAttributes=(ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
            HttpServletRequest request = servletRequestAttributes.getRequest();

            //校验逻辑亲,通过就是true
            return true;
         */
    }

    //我们的webSocket我们可能会传递一些参数的
    //这样的设计允许在 WebSocket 连接的上下文中共享特定的信息。
    @Override
    public void modifyHandshake(ServerEndpointConfig sec, HandshakeRequest request, HandshakeResponse response) {
        //获得请求连接的参数信息
        Map<String, List<String>> parameterMap = request.getParameterMap();
        List<String> erpList = parameterMap.get("erp");     //erp我们约定的就是连接的唯一标识

        //如果有这个参数的话,我们就放到webSocket的上下文中,就是sec
        if(!CollectionUtils.isEmpty(erpList)){
            sec.getUserProperties().put("erp", erpList.get(0));
        }
    }

}
